<?php
/**
 * Created by PhpStorm.
 * User: 云信
 * Date: 2022/4/20
 * Time: 14:49
 */
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\RequestException;
use App\Facades\Data;
use App\Helpers\SystemHelper;
use Illuminate\Http\Exceptions\HttpResponseException;

/**
 * @param $url
 * @param string $method
 * @param array $params
 * @param int $is_as_form
 * 是否用application/x-www-form-urlencoded格式发送
 * @return array
 * 基础Http请求
 */
function http_request($url,$method='GET',$params=[],$is_as_form=0){
    try{
        if($method=='GET'){
            $response=Http::get($url);
        }else{
            #is_as_form
            if($is_as_form==1){
                $response=Http::asForm()->post($url,$params);
            }else{
                $response=Http::post($url,$params);
            }
        }
        #这里throw一个可以catch的异常 TODO
        $response->throwIf($response->failed());
        return json_decode($response->body(),true);
    }catch(RequestException $e){
        Data::set(SystemHelper::HTTP_SERVER_ERROR,$e->getMessage());
        throw (new HttpResponseException(response()->json(Data::returnMsg())));
    }
}

//默认POST格式
function jx_http_request($url,$method='GET',$params=[],$is_as_form=0){
    $res=http_request($url,$method,$params,$is_as_form);
    if($res['Flag']!==0){
        Data::set(SystemHelper::HTTP_SERVER_ERROR,$res['Msg']);
        throw (new HttpResponseException(response()->json(Data::returnMsg())));
    }
    return $res;
}

function ws_http_request($url,$method='GET',$params=[]){
    $res=http_request($url,$method,$params);
    if($res['code']==10001 || $res['code']==10010){
        return 'access_token limit';
    }elseif($res['code']!==0){
        Data::set(SystemHelper::HTTP_SERVER_ERROR,$res['msg']);
        throw (new HttpResponseException(response()->json(Data::returnMsg())));
    }
    return $res;
}

/**
 * @param $url
 * @param string $method
 * @param array $params
 * @return bool
 * 企业微信Http请求
 */
function qw_http_request($url,$method='GET',$params=[]){
    $res=http_request($url,$method,$params);
    if($res['errcode']!==0){
        Data::set(SystemHelper::HTTP_SERVER_ERROR,$res['errmsg']);
        throw (new HttpResponseException(response()->json(Data::returnMsg())));
    }
    return $res;
}


